package com.project.utils;


import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Date;
import java.util.Properties;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.common.auth.ServiceSignature;
import com.aliyun.oss.common.comm.RequestMessage;
import com.aliyun.oss.internal.SignUtils;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;


public class FileUtils{
	
	private static String endpoint = "";
    private static String accessKeyId = "";
    private static String accessKeySecret = "";
    private static String jxbucketName="hxgk-jx";
    private static String key = "head20160511198964";
    public static String sms_url_yunpian = "";
    public static String sms_url = "";
    public static String pay_center_url = "";
    public static String secretKey= "";
	
	
	 public static void init(){
	    	InputStream inputStream = FileUtils.class.getClassLoader().getResourceAsStream("config.properties");
	        Properties properties = new Properties();
	        try {
				properties.load(inputStream);
			} catch (IOException e) {
				e.printStackTrace();
			}
	        endpoint=properties.getProperty("oss_endpoint");
	        accessKeyId=properties.getProperty("oss_accessKeyId");
	        accessKeySecret=properties.getProperty("oss_accessKeySecret");
	        jxbucketName=properties.getProperty("oss_jx_bucketName");
	        sms_url_yunpian=properties.getProperty("sms_url_yunpian");
	        sms_url=properties.getProperty("sms_url");
	        pay_center_url = properties.getProperty("pay_center_url");
	        secretKey = properties.getProperty("secretKey");
//	        System.out.println(endpoint+" "+accessKeyId+" "+accessKeySecret+" "+bucketName);
	        System.out.println("sms_url:"+sms_url);
	    }
	
	public static void uploadfile(File f,String filename){
		init();
		OSSClient client = new OSSClient(endpoint, accessKeyId, accessKeySecret);
		try {
			client.putObject(jxbucketName, filename, f);
		} catch (OSSException e) {
			e.printStackTrace();
		} catch (ClientException e) {
			e.printStackTrace();
		}
		client.shutdown();
	}
	public static void uploadfile(InputStream in,String filename){
		init();
		OSSClient client = new OSSClient(endpoint, accessKeyId, accessKeySecret);
		try {
			client.putObject(jxbucketName, filename, in);
		} catch (OSSException e) {
			e.printStackTrace();
		} catch (ClientException e) {
			e.printStackTrace();
		}
		client.shutdown();
	}
	
		
	public static String getFilePath(String mykey){
		init();
		OSSClient client = new OSSClient(endpoint, accessKeyId, accessKeySecret);
		Date expiration = new Date(new Date().getTime() + 3600 * 1000);// 生成URL
		URL url = client.generatePresignedUrl(jxbucketName, mykey, expiration);
		System.out.println(url);
		return url.toString();
	}
	
	public static String getSmarllFilePath(String mykey){
		init();
		endpoint = "img-cn-qingdao.aliyuncs.com";
		OSSClient client = new OSSClient(endpoint, accessKeyId, accessKeySecret);
    	Date expires = new Date (new Date().getTime() + 1000 * 60*60); // 60 minute to expire
    	GeneratePresignedUrlRequest generatePresignedUrlRequest =
    	new GeneratePresignedUrlRequest(jxbucketName, mykey+"@150h");
    	generatePresignedUrlRequest.setExpiration(expires);
    	URL url = client.generatePresignedUrl(generatePresignedUrlRequest);
		return url.toString();
	}

    public static String generatePresignedUrl(String Expires) {

        RequestMessage requestMessage = new RequestMessage();

        String canonicalResource = "/" + ((jxbucketName != null) ? jxbucketName : "") 
                + ((key != null ? "/" + key : ""));
        String canonicalString = SignUtils.buildCanonicalString("GET", canonicalResource, 
        		requestMessage, Expires);
        String signature = ServiceSignature.create().computeSignature(accessKeyId, canonicalString);

        return signature;
    }
	
	private static File createSampleFile() throws IOException {
        File file = File.createTempFile("oss-java-uploadfile", ".txt");
        Writer writer = new OutputStreamWriter(new FileOutputStream(file));
        writer.write("abcdefghijklmnopqrstuvwxyz\n");
        writer.write("0123456789011234567890\n");
        writer.close();
                                                                                                                               
        return file;
    }

    private static void displayTextInputStream(InputStream input) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(input));
        while (true) {
            String line = reader.readLine();
            if (line == null) break;

            System.out.println("\t" + line);
        }
        System.out.println();

        reader.close();
    }
    
    public static void main(String[] args) {
    	uploadfile(new File("D:\\ivmos\\upload\\schoolDefault.jpg"),"driverschool/head/schoolDefault.jpg");
    	System.out.println(getFilePath("driverschool/head/schoolDefault.jpg"));
    	
    	// Generate a presigned URL
//    	init();
//    	endpoint = "img-cn-qingdao.aliyuncs.com";
//		OSSClient client = new OSSClient(endpoint, accessKeyId, accessKeySecret);
//    	Date expires = new Date (new Date().getTime() + 1000 * 60*60); // 60 minute to expire
//
//    	GeneratePresignedUrlRequest generatePresignedUrlRequest =
//
//    	new GeneratePresignedUrlRequest(bucketName, "1463970079233_xczp_1.jpg@100h");
//
//    	generatePresignedUrlRequest.setExpiration(expires);
//
//    	URL url = client.generatePresignedUrl(generatePresignedUrlRequest);
//
//    	System.out.println(url.toString());
	}
    
    /**
     * <p>Title: downFile</p>
     * <p>Description: 下载文件工具类</p>
     * @param response HttpServletResponse
     * @param filePath 文件路径
     * @param fileName 文件名
     */
    public static void downFile(HttpServletResponse response,String filePath, String fileName) {
    	downFile(response, filePath, fileName, fileName);
    }
    
    /**
     * @Title: downFile
     * @Description: 下载文件工具类
     * @param response HttpServletResponse
     * @param filePath 文件服务器路径
     * @param fileName 文件服务器保存名称
     * @param originalFilename 下载文件时显示的名字（文件上传时的原始文件名）
     */
    public static void downFile(HttpServletResponse response,String filePath, String fileName, String originalFilename) {
    	if(StringUtils.isBlank(fileName)){
    		return;
    	}
    	String path = filePath + "/" + fileName;    
    	File file = new File(path);
    	try {    
    		if (file.exists()) {
    			InputStream ins = new FileInputStream(path);    
    			BufferedInputStream bins = new BufferedInputStream(ins);// 放到缓冲流里面    
    			OutputStream outs = response.getOutputStream();// 获取文件输出IO流    
    			BufferedOutputStream bouts = new BufferedOutputStream(outs);    
    			response.setContentType("application/x-download");// 设置response内容的类型    
    			response.setHeader(    
    					"Content-disposition",    
    					"attachment;filename="    
    							+ URLEncoder.encode(originalFilename, "UTF-8"));// 设置头部信息    
    			int bytesRead = 0;    
    			byte[] buffer = new byte[1024];    
    			//开始向网络传输文件流    
    			while ((bytesRead = bins.read(buffer, 0, 1024)) != -1) {    
    				bouts.write(buffer, 0, bytesRead);    
    			}    
    			bouts.flush();// 这里一定要调用flush()方法    
    			ins.close();    
    			bins.close();    
    			outs.close();    
    			bouts.close();   
    		} else {    
    			response.getWriter().print("<html><script type='text/JavaScript'>alert('找不到下载文件');history.go(-1);</script></html>");
    			response.setContentType("text/html");
    		}    
    	} catch (IOException e) {    
    		e.printStackTrace();  
    	}
    }
    
    public static void downFile(HttpServletResponse response,File file, String originalFilename) {
    	try {    
    		if (file.exists()) {
    			InputStream ins = new FileInputStream(file);    
    			BufferedInputStream bins = new BufferedInputStream(ins);// 放到缓冲流里面    
    			OutputStream outs = response.getOutputStream();// 获取文件输出IO流    
    			BufferedOutputStream bouts = new BufferedOutputStream(outs);    
    			response.setContentType("application/x-download");// 设置response内容的类型    
    			response.setHeader(    
    					"Content-disposition",    
    					"attachment;filename="    
    							+ URLEncoder.encode(originalFilename, "UTF-8"));// 设置头部信息    
    			int bytesRead = 0;    
    			byte[] buffer = new byte[1024];    
    			//开始向网络传输文件流    
    			while ((bytesRead = bins.read(buffer, 0, 1024)) != -1) {    
    				bouts.write(buffer, 0, bytesRead);    
    			}    
    			bouts.flush();// 这里一定要调用flush()方法    
    			ins.close();    
    			bins.close();    
    			outs.close();    
    			bouts.close();   
    		} else {    
    			response.getWriter().print("<html><script type='text/JavaScript'>alert('找不到下载文件');history.go(-1);</script></html>");
    			response.setContentType("text/html");
    		}    
    	} catch (IOException e) {    
    		e.printStackTrace();  
    	}
    }
    
    public static void decodeWithJava(String content, String imageName) {
		byte[] decode = java.util.Base64.getDecoder().decode(content.trim());
		File image = new File(imageName);
		 //判断路径是否存在，如果不存在就创建一个
        if (!image.getParentFile().exists()) { 
        	image.getParentFile().mkdirs();
        }
		try {
			OutputStream out=new FileOutputStream(image);
			out.write(decode);
			out.flush();
			out.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
    
    /**
     * <p>将文件转成base64 字符串</p>
     * @param path 文件路径
     * @return
     * @throws Exception
     */
     public static String encodeBase64File(String path){
         try {
			File file = new File(path);
			 FileInputStream inputFile = new FileInputStream(file);
			 byte[] buffer = new byte[(int)file.length()];
			 inputFile.read(buffer);
			 inputFile.close();
			 return java.util.Base64.getEncoder().encodeToString(buffer);
		} catch (Exception e) {
			e.printStackTrace();
		}
         return null;
     }
    
}
